import datetime

from rest_framework.decorators import action
from rest_framework.mixins import ListModelMixin, RetrieveModelMixin, CreateModelMixin
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response

from social.feed.models import PostLike
from social.notification.models import Notification, NotificationRead
from social.notification.serializers import NotificationSerializer
from social.user.models import UserVisit, UserLike
from social.utils.shortcut import get_object_or_none
from social.utils.views import BaseGenericViewSet, UpdateModelMixin


class NotificationViewSet(BaseGenericViewSet, ListModelMixin, RetrieveModelMixin, CreateModelMixin, UpdateModelMixin):
    queryset = Notification.objects.select_related('user')
    serializer_class = NotificationSerializer
    permission_classes = (IsAuthenticated,)
    pagination_ordering = '-created_at'

    def list(self, request, *args, **kwargs):
        _next = request.GET.get('next')
        if not _next:
            read = get_object_or_none(NotificationRead, user=request.user)
            read.new_post_msg = datetime.datetime.now().timestamp()
            read.save(update_fields=['new_post_msg'])
        self.queryset = self.queryset.select_related('from_user').filter(user=request.user)
        return super(NotificationViewSet, self).list(request, *args, **kwargs)

    @action(methods=['GET'], detail=False)
    def unread(self, request, *args, **kwargs):
        read, _ = NotificationRead.objects.get_or_create(user=request.user)
        new_post_msg = Notification.objects.filter(
            created_at__gt=datetime.datetime.fromtimestamp(read.new_post_msg), user=request.user).count()
        new_visit = UserVisit.objects.filter(to_user=request.user,
                                             created_at__gt=datetime.datetime.fromtimestamp(read.new_visitor)).count()
        new_fans = UserLike.objects.filter(to_user=request.user,
                                           created_at__gt=datetime.datetime.fromtimestamp(read.new_fans)).count()
        return Response(data={
            'new_post_msg': new_post_msg,
            'new_visit': new_visit,
            'new_fans': new_fans
        })
